import _ from 'lodash-es'
import Vue from 'vue'
import Router from 'vue-router'
import { PROJECT_NAME, PROJECT_NAME_CN, PREFIX } from '@/app-config'

let base = PROJECT_NAME
if (PREFIX) {
    base = `${PREFIX}/${PROJECT_NAME}`
}
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(error => error)
}
const originalReplace = Router.prototype.replace
Router.prototype.replace = function push(location) {
    return originalReplace.call(this, location).catch(error => error)
}

Vue.use(Router)

const files = require.context('./views', true, /router\.js$/)

const router = new Router({
    mode: 'history',
    base,
    routes: [
        {
            path: '/',
            name: 'index',
            redirect: {
                name: 'admin',
            },
        },
        {
            path: '/auth',
            name: 'auth',
            component: () => import('@/views/auth.vue'),
            meta: {
                pass: true,
            },
        },
        ..._.reduce(
            files.keys(),
            (result, item) => {
                const module = _.get(item.match(/\.\/(.*)\/router\.js/), '[1]', '')
                result.push(
                    ...files(item).default.map(route => {
                        route = _.cloneDeep(route)
                        const { children } = route
                        _.merge(route, {
                            meta: {
                                module,
                            },
                        })
                        // 添加子路由所属模块
                        if (children && !_.isEmpty(children)) {
                            route.children = _.map(children, child =>
                                _.set(child, 'meta.module', module)
                            )
                        }

                        return route
                    })
                )
                return result
            },
            []
        ),
    ],
})

router.beforeEach(async (to, from, next) => {
    document.title = _.get(to, 'meta.pageName', PROJECT_NAME_CN)
    next()
})

export default router
